package com.dunke.web.interceptor;


import com.dunke.core.common.Result;
import com.dunke.core.common.TokenData;
import com.dunke.core.enums.ReturnCode;
import com.dunke.constants.Constants;
import com.dunke.utils.DateUtils;
import com.dunke.utils.JedisUtil;
import com.dunke.utils.TokenUtil;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录拦截器类
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    TokenUtil tokenUtil ;

    /**
     * preHandle是请求执行前执行的
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object o) throws Exception {
        // 获取Token
        String token = request.getHeader("token");
        /**
         * 未登录
         */
        if(StringUtils.isBlank(token)){
            NotLogin(response);
            return false ;
        }

        JedisUtil jedis = new JedisUtil();
        TokenData tokenData = jedis.getToken(token);

        /**
         * Token 无效
         */
        if (tokenData == null) {
            TokenUnusual(response);
            return false;
        }

        // token存在时长=当前时间-创建token的时间
        long diff = DateUtils.getCurrentMillis() - tokenData.getCreateTime();

        /**
         * 判断Token是否过期
         */
        if (diff < Constants.TOKEN_EXPIRE_TIME && diff >= 0) {
            /**
             * 未过期且在刷新条件内，刷新过期时间
             */
            if ((Constants.TOKEN_EXPIRE_TIME - diff) >= Constants.TOKEN_RESET_TIME) {
                tokenData.setCreateTime(System.currentTimeMillis());
                jedis.setToken(tokenData);
            }
            return true;
        }
        TokenExpire(response);
        return false;
    }

    /**
     * 未登录
     * @param response
     * @throws IOException
     */
    private void NotLogin(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(new Gson().toJson(
                Result.error(ReturnCode.USER_NOT_LOGIN)));
    }

    /**
     * Token 异常
     * @param response
     * @throws IOException
     */
    private void TokenUnusual(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(new Gson().toJson(
                        Result.error(ReturnCode.USER_TOKEN_UNUSUAL)));
    }

    /**
     * Token 过期
     * @param response
     * @throws IOException
     */
    private void TokenExpire(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(new Gson().toJson(
                Result.error(ReturnCode.USER_TOKEN_EXPIRE)));
    }

}
